package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.order.entity.dos.RankingActivityConfig;
import cn.lili.modules.order.order.entity.dos.RankingAwardDetails;
import cn.lili.modules.order.order.entity.dos.RankingScoreDetails;
import cn.lili.modules.order.order.entity.dto.RankingAwardDetailsDTO;
import cn.lili.modules.order.order.entity.dto.RankingScoreDetailsDTO;
import cn.lili.modules.order.order.entity.dto.TopUserDTO;
import cn.lili.modules.order.order.entity.enums.RankingAwardOrderStatusEnum;
import cn.lili.modules.order.order.entity.vo.RankingScoreDetailsVO;
import cn.lili.modules.order.order.mapper.RankingScoreDetailsMapper;
import cn.lili.modules.order.order.service.IRankingAwardDetailsService;
import cn.lili.modules.order.order.service.IRankingScoreDetailsService;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 积分记录表 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RankingScoreDetailsServiceImpl extends ServiceImpl<RankingScoreDetailsMapper, RankingScoreDetails> implements IRankingScoreDetailsService {

    private final IRankingAwardDetailsService rankingAwardDetailsService;
    private final UserClient userClient;
    /**
     * 分页
     *
     * @return
     */
    @Override
    public ResultMessage<Object> scorePage(RankingScoreDetails scoreDetails, PageVO pageVO) {
        Page<RankingScoreDetails> page = super.page(PageUtil.initPage(pageVO), this.createWrapper(scoreDetails));
        return ResultUtil.data(page);
    }

    @Override
    public List<TopUserDTO> topUser(RankingActivityConfig currentActivity, Double sc, Integer status) {
        return baseMapper.topUser(currentActivity, sc, status);
    }

    @Override
    public List<TopUserDTO> topUserLimit(RankingActivityConfig currentActivity, Double sc, Integer status, Integer limit1, Integer limit2) {
        return baseMapper.topUserLimit(currentActivity, sc, status, limit1, limit2);
    }

    /**
     * 创建条件
     *
     * @param scoreDetails 参数
     * @return 条件
     */
    private Wrapper<RankingScoreDetails> createWrapper(RankingScoreDetails scoreDetails) {
        LambdaQueryWrapper<RankingScoreDetails> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取分销员的积分
        detailsLambdaQueryWrapper.eq(RankingScoreDetails::getParentUserId, UserContext.getCurrentId());
        if (StringUtils.isNotEmpty(scoreDetails.getCurrentActivityId())) {
            detailsLambdaQueryWrapper.eq(RankingScoreDetails::getCurrentActivityId, scoreDetails.getCurrentActivityId());
        }
        //退款的积分不计算
        detailsLambdaQueryWrapper.ne(RankingScoreDetails::getOrderStatus, DictConstant.SCORE_ORDER_STATUS_03);
        detailsLambdaQueryWrapper.eq(RankingScoreDetails::getDeleteFlag, Boolean.FALSE);
        detailsLambdaQueryWrapper.orderByDesc(RankingScoreDetails::getCreateTime);
        return detailsLambdaQueryWrapper;
    }

    /**
     * 根据活动id获取积分排名列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Page<RankingScoreDetailsVO>> getRankingScoreDetail(RankingScoreDetailsDTO dto) {
        if (StringUtils.isNotEmpty(dto.getSortOrder()) && dto.getSortOrder().contains("normal")) {
            dto.setSortOrder(null);
        }
        Page<RankingScoreDetailsVO> rankingListPage = baseMapper.getRankingScoreDetail(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto);
        if (CollUtil.isNotEmpty(rankingListPage.getRecords())) {
            //排列排名
            rankingListPage.getRecords().forEach(e -> e.setRanking(
                    (dto.getPageNumber() > 1 ? dto.getPageNumber() + dto.getPageSize() - 1 : 0) +
                            rankingListPage.getRecords().indexOf(e) + 1)
            );

            List<String> userIds = rankingListPage.getRecords().stream().map(RankingScoreDetailsVO::getUserId).collect(Collectors.toList());
            //查询奖品名细
            RankingAwardDetailsDTO awardDto = new RankingAwardDetailsDTO();
            awardDto.setUserIds(userIds);
            awardDto.setActivityId(dto.getActivityId());
            List<RankingAwardDetails> dommainDetails = rankingAwardDetailsService.selectListByDto(awardDto);

            //查询用户昵称,账号
            List<User> userInfos = userClient.selectUserListByIds(userIds);
            Map<String,User> userMap = new HashMap<>();
            if (CollUtil.isNotEmpty(userInfos)) {
                userMap = userInfos.stream().collect(Collectors.toMap(User::getId, v -> v));
            }
            //领奖信息
            if (CollUtil.isNotEmpty(dommainDetails)) {
                //转map
                Map<String, RankingAwardDetails> map = dommainDetails.stream().collect(Collectors.toMap(RankingAwardDetails::getUserId, v -> v));
                for (RankingScoreDetailsVO vo : rankingListPage.getRecords()) {
                    if (ObjectUtil.isNotNull(map.get(vo.getUserId()))) {
                        //收货地址
                        vo.setDeliveryAddress(StringUtils.isNotEmpty(map.get(vo.getUserId()).getDeliveryAddress()) ? map.get(vo.getUserId()).getDeliveryAddress() : "");
                        //昵称
                        vo.setNickName(map.get(vo.getUserId()).getNickName());
                        //奖品名称
                        vo.setAwardName(map.get(vo.getUserId()).getAwardName());
                        //奖品明细id
                        vo.setRankingAwardDetailsId(map.get(vo.getUserId()).getId());
                        vo.setAwardStatus(map.get(vo.getUserId()).getAwardStatus());
                    }
                    //赋值:账号,昵称
                    if (CollUtil.isNotEmpty(userMap) && null != userMap.get(vo.getUserId())) {
                        vo.setAccount(StringUtils.isNotEmpty(userMap.get(vo.getUserId()).getAccount()) ? userMap.get(vo.getUserId()).getAccount() : vo.getNickName());
                        vo.setFyName(StringUtils.isNotEmpty(userMap.get(vo.getUserId()).getFyName()) ? userMap.get(vo.getUserId()).getFyName() : userMap.get(vo.getUserId()).getNickName());
                    }
                }
            }

            dto.setUserIds(userIds);
            //未结算
            dto.setOrderStatus(1);
            List<RankingScoreDetailsVO> unsettledScoreList = baseMapper.selectSettledScoreByUserIds(dto);
            //已结算
            dto.setOrderStatus(2);
            List<RankingScoreDetailsVO> settledScoreList = baseMapper.selectSettledScoreByUserIds(dto);
            //未结算
            if (CollUtil.isNotEmpty(unsettledScoreList)) {
                //转成map
                Map<String, RankingScoreDetailsVO> unsettledScoreMap = unsettledScoreList.stream().collect(Collectors.toMap(RankingScoreDetailsVO::getUserId, v -> v));
                for (RankingScoreDetailsVO e : rankingListPage.getRecords()) {
                    RankingScoreDetailsVO unsettledVo = unsettledScoreMap.get(e.getUserId());
                    if (null != unsettledVo && null != unsettledVo.getTotalScore()) {
                        e.setUnsettledScore(unsettledVo.getTotalScore());
                    }
                }
            }
            //已结算
            if (CollUtil.isNotEmpty(settledScoreList)) {
                //转成map
                Map<String, RankingScoreDetailsVO> settledScoreMap = settledScoreList.stream().collect(Collectors.toMap(RankingScoreDetailsVO::getUserId, v -> v));
                for (RankingScoreDetailsVO e : rankingListPage.getRecords()) {
                    RankingScoreDetailsVO unsettledVo = settledScoreMap.get(e.getUserId());
                    if (null != unsettledVo && null != unsettledVo.getTotalScore()) {
                        e.setSettledScore(unsettledVo.getTotalScore());
                    }
                }
            }
        }
        return ResultUtil.data(rankingListPage);
    }


    /**
     * 根据用户id获取积分明细商品列表 总积分详情-->商品明细列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Page<RankingScoreDetails>> getRankingScoreDetailByUserId(RankingScoreDetailsDTO dto) {
        if (null == dto.getUserId()) {
            return ResultUtil.error(400, "用户id不能为空");
        }
        if (null == dto.getActivityId()) {
            return ResultUtil.error(400, "活动id不能为空");
        }
        LambdaQueryWrapper<RankingScoreDetails> query = new LambdaQueryWrapper<>();
        query.eq(RankingScoreDetails::getParentUserId, dto.getUserId());
        query.eq(RankingScoreDetails::getCurrentActivityId, dto.getActivityId());
        query.orderByDesc(RankingScoreDetails::getCreateTime).orderByDesc(RankingScoreDetails::getId);
        log.info("#getRankingScoreDetailByUserId# 条件打印:{}", query.getSqlSegment());
        Page<RankingScoreDetails> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), query);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            //更改productName内容
            page.getRecords().stream().forEach(e ->
                    e.setProductName(e.getOrderStatus() == RankingAwardOrderStatusEnum.REFUNDED.code ? e.getProductName().join(",").join(RankingAwardOrderStatusEnum.REFUNDED.name) : e.getProductName())
            );
            log.info("#getRankingScoreDetailByUserId# 查询结果条数为:{}", page.getTotal());
            return ResultUtil.data(page);
        }
        return ResultUtil.data(new Page<>());
    }

    /**
     * 店主列表->总佣金详情列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Page<RankingScoreDetails>> getDistributeionSubCommissDetails(RankingScoreDetailsDTO dto) {
        //判断用户id不可为null
        if (StringUtils.isEmpty(dto.getUserId())) {
            return ResultUtil.error(400, "用户id不能为空");
        }
        LambdaQueryWrapper<RankingScoreDetails> query = new LambdaQueryWrapper<>();
        query.eq(RankingScoreDetails::getParentUserId, dto.getUserId());
        query.eq(RankingScoreDetails::getDeleteFlag, Boolean.FALSE);
        if (StringUtils.isNotEmpty(dto.getActivityId())) {
            query.eq(RankingScoreDetails::getCurrentActivityId, dto.getActivityId());
        }
        //时间范围
        if (StringUtils.isNotEmpty(dto.getStartTime()) && StringUtils.isNotEmpty(dto.getEndTime())) {
            query.ge(RankingScoreDetails::getCreateTime, dto.getStartTime());
            query.le(RankingScoreDetails::getCreateTime, dto.getEndTime());
        }
        if (StringUtils.isNotEmpty(dto.getBuyerUserId())) {
            query.eq(RankingScoreDetails::getBuyerUserId, dto.getBuyerUserId());
        }

        //订单状态
        if (null != dto.getOrderStatus()) {
            query.eq(RankingScoreDetails::getOrderStatus, dto.getOrderStatus());
        }
        log.info("#getDistributeionSubCommissDetails# 条件打印:{}", query.getSqlSegment());
        query.orderByDesc(RankingScoreDetails::getCreateTime).orderByDesc(RankingScoreDetails::getId);
        Page<RankingScoreDetails> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), query);
        log.info("#getDistributeionSubCommissDetails# 查询结果条数为:{}", page.getTotal());
        return ResultUtil.data(page);
    }

    @Override
    public BigDecimal currentScore(RankingActivityConfig currentActivity) {
        return baseMapper.currentScore(currentActivity, UserContext.getCurrentId());
    }
}
